import React, { PureComponent, Fragment } from 'react'
import { Form, Input, Button, Select, Skeleton, Upload, Switch, Space, message } from 'antd'
import { InboxOutlined } from '@ant-design/icons'
import { uploadImage, updateBook, deleteBook, reshowBook, addBook } from './ActionCreators'
import {
  detailData
} from '@/Redux/ActionTypes/MallManagement/MallManagementActionCreators'
import './index.css'
import { connect } from 'react-redux'
import { history } from '@/index'

const formItemLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 14 },
}

const tailLayout = {
  wrapperCol: {
    offset: 11,
    span: 16,
  },
}

const mapStateToProps = (state) => {
  return {
    goodsStatus: state.mallManagement.goods_status,
    selectedData: state.baseTable.selectedData,
    bookDetail: state.mallManagement.book_detail,
    dataLoading: state.mallManagement.book_loading
  }
}
const mapDispatchToProps = (dispatch) => ({
  setDetailData(...rest) {
    return dispatch(detailData(...rest))
  }
})
@connect(mapStateToProps, mapDispatchToProps)
class goodsInfo extends PureComponent {
  state = {
    url: null,
    id: null,
    coverImg: null,
    submitLoading: false,
    dataLoading: true,
    initial: null
  }

  formRef = React.createRef(this);

  componentDidMount() {
    this.getDefaultData()
    this.formRef && this.formRef.current?.setFieldsValue({ ...this.props.bookDetail, url: null })
  }

  componentDidUpdate() {
    this.getDefaultData()
    this.formRef && this.formRef.current?.setFieldsValue({ ...this.props.bookDetail, url: null })
  }

  componentWillUnmount() {
    this.props.setDetailData({})
    this.setState({
      id: null,
      coverImg: null,
      submitLoading: false,
      dataLoading: true,
      initial: null
    })
  }

  getDefaultData() {
    if (this.props.goodsStatus === 'new') {
      this.setState({
        dataLoading: false
      })
    } else {
      const id = this.props.selectedData.id
      this.setState({
        id,
        dataLoading: false,
      })
    }
  }

  async handleSumbit(value) {
    this.setState({
      submitLoading: true
    })
    let data = {}
    for (var title in value) {
      if (!value[title]) {
        if (title === 'discount') {
          value[title] = false
        } else {
          value[title] = '无'
        }
      } else if (title === 'discount' && value['discount'] === false) {
        delete value['discountedPrice']
      } else if (title === 'url' && value[title].length === 0) {
        value[title] = '无'
      }
    }
    data = { ...value }
    this.formRef && this.formRef.current?.setFieldsValue({ ...data, url: null })
    if (Array.isArray(data.url) || this.props.bookDetail.url) {
      try {
        message.info('正在上传中')
        if (Array.isArray(data.url)) {
          const url = await uploadImage(value.url[0].originFileObj)
          data.url = url.data.data
        } else {
          data.url = this.props.bookDetail.url
        }
        let res = null
        if (this.props.goodsStatus === 'new') {
          res = await addBook(data)
        } else {
          data.id = this.state.id
          res = await updateBook(data)
        }
        if (res.data.success) {
          message.success('上传成功')
          history.push('/homePage/mallManagement/goods')
        } else {
          this.props.setDetailData(data)
          message.error('上传失败')
        }
      } catch {
        this.props.setDetailData(data)
        message.error('上传失败')
      }
    } else {
      if (data.url === '无') {
        data.url = null
      }
      this.props.setDetailData(data)
      message.error('请传入封面')
    }
    this.setState({
      submitLoading: false
    })
  }

  beforeUpload(e) {
    return false
  }

  normFile(e) {
    if (Array.isArray(e)) {
      return e;
    }

    return e && e.fileList;
  };

  async deleteBook() {
    this.setState({
      deleteLoading: true
    })
    if (this.props.goodsStatus === 'new') {
      message.success('删除成功')
      history.push('/homePage/mallManagement/goods')
    } else {
      const res = await deleteBook(this.state.id)
      if (res.data.success) {
        message.success('下架成功')
        history.push('/homePage/mallManagement/goods')
      } else {
        message.error('下架失败')
        this.setState({
          deleteLoading: false
        })
      }
    }
  }

  render() {
    return (
      this.props.dataLoading ? <Skeleton active></Skeleton> :
        <div style={{ marginLeft: '10%' }}>
          <div style={{ fontWeight: '700' }}>商品信息</div>
          <Form
            className='goods-info-form'
            {...formItemLayout}
            style={{ marginLeft: '130px' }}
            ref={this.formRef}
            scrollToFirstError={true}
            onFinish={value => this.handleSumbit(value)}
          >
            <div className="book-info-title">书籍封面</div>
            <Form.Item label="上传图片">
              <Form.Item name="url" noStyle valuePropName="fileList" getValueFromEvent={this.normFile}>
                <Upload.Dragger name="files" beforeUpload={this.beforeUpload} maxCount={1} >
                  <p className="ant-upload-drag-icon">
                    <InboxOutlined />
                  </p>
                  <p className="ant-upload-text">点击或者拖拽上传</p>
                </Upload.Dragger>
              </Form.Item>
            </Form.Item>
            <div className="book-info-title">商品基础信息</div>
            <Form.Item
              label="商品名称"
              name="title"
              rules={[{ required: true, message: '请输入商品名称' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="作者"
              name="writer"
              rules={[{ required: true, message: '请输入作者名字' }]}>
              <Input />
            </Form.Item>
            <Form.Item
              label='类别'
              name='type'
              rules={[{ required: true, message: '请填写类别' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="书籍简介"
              name="introduce"
              rules={[{ required: false }]}>
              <Input.TextArea />
            </Form.Item>
            <Form.Item
              label="出版商"
              name="publisher"
              rules={[{ required: true, message: '请输入出版商名字' }]}>
              <Input />
            </Form.Item>
            <Form.Item
              label="价格"
              name="price"
              rules={[{ required: true, message: '请输入商品价格' }]}>
              <Input />
            </Form.Item>
            <Form.Item
              label='是否打折'
              name='discount'
              valuePropName="checked"
            >
              <Switch checkedChildren="是" unCheckedChildren="否" />
            </Form.Item>
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) => prevValues.discount !== currentValues.discount}
            >
              {({ getFieldValue }) =>
                getFieldValue('discount') === true ? (
                  <Form.Item
                    name="discountedPrice"
                    label="折扣价"
                    rules={[
                      {
                        required: true,
                      },
                    ]}
                  >
                    <Input />
                  </Form.Item>
                ) : null}
            </Form.Item>
            {/* <div className="book-info-title">商品详情图</div> */}
            {/* <Form.Item label="上传图片">
            <Form.Item name="detailimg" noStyle valuePropName="fileList">
              <Upload.Dragger name="files" beforeUpload={this.beforeUpload}>
                <p className="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p className="ant-upload-text">点击或者拖拽上传</p>
              </Upload.Dragger>
            </Form.Item>
          </Form.Item> */}
            <Form.Item {...tailLayout}>
              <Space>
                <Button type="primary" loading={this.state.submitLoading} htmlType="submit">
                  上传
                </Button>
                <Button htmlType="button" onClick={() => { this.deleteBook() }}>
                  {this.props.goodsStatus === 'new' ? '删除' : '下架'}
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </div>
    )
  }
}

export default goodsInfo